package com.chj.comp.common.db.util;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.chj.comp.common.core.constant.EncryptAndDecryptConstant;
import com.chj.comp.common.core.util.AESUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 自定义TypeHandler，当使用mybatis plus内置方法时，自动加解密处理
 * ps：@TableField(value = "phone",typeHandler = AesTypeHandler.class)
 *
 * @author cuihui
 * @date 2022/03/11
 */

/** 数据库中的数据类型 */
@MappedJdbcTypes(JdbcType.VARCHAR)
/** 处理后的数据类型 */
@MappedTypes(value = String.class)
@Slf4j
public class AesTypeHandler extends BaseTypeHandler {

    private static final String  DEFAULT_KEY = EncryptAndDecryptConstant.DATA_ENCRYPT_KEY;

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {
        log.info("AesTypeHandler------>setNonNullParameter");
        log.info("parameter------->" + parameter);
        if (parameter != null && StringUtils.isNotBlank((String) parameter)){
            ps.setString(i, AESUtil.encryptAESECB((String) parameter,DEFAULT_KEY));
        }else{
            ps.setString(i, (String) parameter);
        }
    }

    @Override
    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        log.info("AesTypeHandler------>getNullableResult");
        log.info("rs.toString()------------->" + rs.toString());
        log.info("columnName---------->" + columnName);
        log.info(" rs.getString(columnName)---------->" +  rs.getString(columnName));
        return StringUtils.isBlank(rs.getString(columnName)) ? rs.getString(columnName) : AESUtil.decryptAESECB(rs.getString(columnName),DEFAULT_KEY);
    }

    @Override
    public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        log.info("AesTypeHandler------>getNullableResult");
        log.info("rs.toString()------------->" + rs.toString());
        log.info("columnIndex---------->" + columnIndex);
        return StringUtils.isBlank(rs.getString(columnIndex)) ? rs.getString(columnIndex) : AESUtil.decryptAESECB(rs.getString(columnIndex),DEFAULT_KEY);
    }

    @Override
    public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        log.info("AesTypeHandler------>getNullableResult");
        log.info("cs.toString()------------->" + cs.toString());
        log.info("columnIndex---------->" + columnIndex);
        return StringUtils.isBlank(cs.getString(columnIndex)) ? cs.getString(columnIndex) : AESUtil.decryptAESECB(cs.getString(columnIndex),DEFAULT_KEY);
    }
}
